import logging
import enum
from redis import StrictRedis
from django.conf import settings
from common.es_core.es_interface import es_search_interface
from storage.rawdata.bypass_proxy import BypassProxyRawDataStorage
from preprocessor.dwc.model_router import ACCOUNT_MODEL_ROUTER
from common.utils.maestro_exceptions import (
    MaestroException,
    ERROR_USER_NOT_EXISTS,
    SERVER_ERROR
)

_LOGGER = logging.getLogger(__name__)

redis = StrictRedis.from_url(settings.CONSUMER_REDIS, charset="utf-8", decode_responses=True)


class MarketingPlatformType(enum.Enum):
    AGENT = 'agent'
    FRIDAY = 's2s'
    QK = 'qk'
    CHANNEL = '_chn'


def manual_bind_appid(platform_id, user_id, marketing_platform_type, app_id):
    assert isinstance(marketing_platform_type, MarketingPlatformType)
    assert platform_id in ACCOUNT_MODEL_ROUTER, u'平台号不存在'
    table = ACCOUNT_MODEL_ROUTER[platform_id]
    user = table.objects.filter(user_id=user_id).first()
    if not user:
        raise MaestroException(ERROR_USER_NOT_EXISTS)
    if marketing_platform_type.value in (MarketingPlatformType.FRIDAY.value, MarketingPlatformType.AGENT.value,
                                         MarketingPlatformType.QK.value):
        if marketing_platform_type.value == MarketingPlatformType.FRIDAY.value:
            user.extra_info, es_field_key = app_id, '_s2s_appid'
        elif marketing_platform_type.value == MarketingPlatformType.AGENT.value:
            user.agent_chn, es_field_key = app_id, '_agent_chn'
        else:  # AppidType.QK.value
            user.qk_appid, es_field_key = app_id, '_qk_appid'
    else:
        user.channel, es_field_key = app_id, '_chn'
    account_redis_key = 'dwc:{}:account:{}'.format(platform_id, user_id)
    redis.delete(account_redis_key)
    tag_agent_chn_to_previous_event(platform_id, user_id, es_field_key, app_id)
    user.save()


def tag_agent_chn_to_previous_event(platform_id, user_id, es_field_key, appid, default_size=1000):
    assert es_field_key in ('_s2s_appid', '_agent_chn', '_qk_appid', '_chn')
    query_dsl = {
        "query": {
            "bool": {
                "filter": [
                    {"term": {"_user_id": user_id}}
                ]
            }
        },
        "size": default_size
    }
    resp_json = es_search_interface(platform_id, query_dsl)
    if resp_json['hits']['total'] > default_size:
        if resp_json['hits']['total'] > 20000:
            raise MaestroException(SERVER_ERROR)
        query_dsl['size'] = resp_json['hits']['total']
        resp_json = es_search_interface(platform_id, query_dsl)
    storage = BypassProxyRawDataStorage(platform_id)
    for each in resp_json['hits']['hits']:
        event = each['_source']
        event['_id'] = each['_id'][len(event['_event_id']) + 1:]
        event[es_field_key] = appid
        event[es_field_key + '_bind_update'] = 1
        storage.add_batch([event])
    storage.execute_batch()


def get_user_channel_for_marketing_platform(platform_id, user_id, marketing_platform_type):
    assert platform_id in ACCOUNT_MODEL_ROUTER, u'平台号不存在'
    table = ACCOUNT_MODEL_ROUTER[platform_id]
    user = table.objects.filter(user_id=user_id).first()
    if not user:
        raise MaestroException(ERROR_USER_NOT_EXISTS)
    if marketing_platform_type.value == MarketingPlatformType.FRIDAY.value:
        bind_chn = user.extra_info if user.extra_info else user.channel
        app_id_binded = 1 if user.extra_info else 0
    elif marketing_platform_type.value == MarketingPlatformType.AGENT.value:
        bind_chn = user.agent_chn if user.agent_chn else user.channel
        app_id_binded = 1 if user.agent_chn else 0
    else:  # AppidType.QK.value
        bind_chn = user.qk_appid if user.qk_appid else user.channel
        app_id_binded = 1 if user.qk_appid else 0
    return dict(bind_chn=bind_chn, user_id=user_id, created_at=str(user.registered_at), app_id_binded=app_id_binded)
